package com.cw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.entity.dto.SetmealDto;
import com.cw.entity.Setmeal;
import com.cw.entity.SetmealDish;
import com.cw.handler.CustomException;
import com.cw.mapper.SetmealMapper;
import com.cw.service.SetmealDishService;
import com.cw.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService  {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        log.info("保存的菜品为：{}",setmealDto);

        //1.保存基础属性
        this.save(setmealDto);

        //2.为每个属性添加id
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes().stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //3.保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishList);


    }

    /**
     * 批量删除套餐
     * @param ids
     */
    @Override
    public void deleteById(List<Long> ids) {
        //select count(*)  from setmeal in(1,2,3,4) where status = 1
        QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        wrapper.eq("status",1);
        int count = this.count(wrapper);


        if (count>0){
            throw new CustomException("套餐在售，无法删除");
        }

        //删除数据
        this.removeByIds(ids);

        //删除相关联菜品
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.removeByIds(ids);
    }
}
